package com.py.credit.utils;


import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
 
 
public class HttpsUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpsUtil.class);
 
 
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
 
    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
 
    public static String sendHtpps(String url,String method) {
        String result = "";
        BufferedReader in = null;
        HttpURLConnection conn;
        InputStream inputStream = null;
        OutputStreamWriter out = null;
        try {
            trustAllHosts();
            URL realUrl = new URL(url);
            // 通过请求地址判断请求类型(http或者是https)
            if (realUrl.getProtocol().toLowerCase().equals("https")) {
                HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod(method);
         
 
 
            conn.connect();
            if( conn.getResponseCode() == 200){
                inputStream = conn.getInputStream();
                String ck = conn.getHeaderField("Set-Cookie");
                System.out.println("cookie:"+ck);
            }else{
                inputStream = conn.getErrorStream();
            }
 
            in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("https request error:" + e);
 
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
 
 
    public static String getCookie(String url) {
        String cookie = "";
        String result = "";
        BufferedReader in = null;
        HttpURLConnection conn;
        InputStream inputStream = null;
        OutputStreamWriter out = null;
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userName", "11");
        paramMap.put("password", "11@123");
        paramMap.put("serverIp", "192.168.11.1");
        paramMap.put("serverPort", "1111");
        try {
            trustAllHosts();
            URL realUrl = new URL(url);
            // 通过请求地址判断请求类型(http或者是https)
            if (realUrl.getProtocol().toLowerCase().equals("https")) {
                HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(JSONObject.toJSONString(paramMap));
            out.flush();
            out.close();
            conn.connect();
            if( conn.getResponseCode() == 200){
                inputStream = conn.getInputStream();
                 cookie = conn.getHeaderField("Set-Cookie");
            }else{
                inputStream = conn.getErrorStream();
            }
 
            in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
 
            logger.info("登录接口响应{}",result);
            if(StringUtils.isNotEmpty(result)){
                JSONObject responseObject = JSONObject.parseObject(result);
                int resultCode = (int) responseObject.get("resultCode");
                if(resultCode == 0){
                    return cookie;
                }else{
                    return null;
                }
            }else{
                return "";
            }
        } catch (Exception e) {
            logger.info("https request error:" + e);
 
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return cookie;
    }
 
    private static void trustAllHosts() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[] {};
            }
 
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
 
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        } };
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) throws Exception {
        HttpsUtil.sendHtpps("https://222.143.33.180:8443/creditdatas/ws/xyjgService?wsdl","POST");
    }
}